import { Component, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import {
  OpscopeService,
  Pageable,
  Scope,
  SysroleService,
} from 'sparrow-permission-lib';
import { NzTableCommonService } from 'src/app/service/nz-table-common.service';
import { NzTableGetdataScopeService } from 'src/app/service/nz-table-getdata-scope.service';
import { SysroleSearchComponent } from 'src/app/share/sysrole-search/sysrole-search.component';

@Component({
  selector: 'app-scope',
  templateUrl: './scope.component.html',
  styleUrls: ['./scope.component.css'],
})
export class ScopeComponent implements OnInit {
  total: number = 0;
  pageable: Pageable = { page: 1, size: 10 };
  isVisiable: Map<string, boolean> = new Map<string, boolean>();
  tableDataService!: NzTableCommonService;

  constructor(
    private fb: FormBuilder,
    private scopeService: OpscopeService,
    private message: NzMessageService,
    private scopePagedDataService: NzTableGetdataScopeService,
    private sysroleService: SysroleService
  ) {}

  ngOnInit(): void {
    this.isVisiable.set('scopeForm', false);
    this.tableDataService = new NzTableCommonService(
      this.scopePagedDataService,
      this.pageable
    );
  }

  create(scope: Scope | any) {}

  update(id: string, scope: Scope | any) {}

  onDelete(id: string) {
    this.scopeService.delete3([id],'response').subscribe((res) => {
      if(res.status===204){
        this.tableDataService.onPageIndexChange(
          this.tableDataService.pageable.page!
        );
      }else{
        this.message.error('删除失败！请先移除所有关联关系！')
      }

    });
  }

  selectedScope: any;
  isVisiableForScopeForm: boolean = false;
  scopeForm!: FormGroup;
  showScopeDialog(scope: any) {
    if (scope === undefined) {
      this.scopeForm = this.fb.group({
        name: [null, [Validators.required]],
        code: [null, [Validators.required]],
      });
      this.selectedScope = undefined;
    } else {
      this.scopeForm = this.fb.group({
        name: [scope.name, [Validators.required]],
        code: [scope.code, [Validators.required]],
      });
      this.selectedScope = scope;
    }

    this.isVisiableForScopeForm = true;
  }

  onScopeFormSubmit() {
    console.log(this.scopeForm.value);
    if (!this.scopeForm.valid) {
      for (const i in this.scopeForm.controls) {
        if (this.scopeForm.controls.hasOwnProperty(i)) {
          this.scopeForm.controls[i].markAsDirty();
          this.scopeForm.controls[i].updateValueAndValidity();
        }
      }
    } else {
      let scope = this.scopeForm.value;
      if (this.selectedScope === undefined) {
        this.scopeService.create4(scope, 'response').subscribe((res: any) => {
          if (res.status != 201) {
            this.message.error(res.body);
          } else {
            this.ngOnInit();
            this.isVisiableForScopeForm = false;
          }
        });
      } else {
        let updateScope: any = {};
        if (scope.name != this.selectedScope.name) {
          updateScope.name = scope.name;
        }
        if (scope.code != this.selectedScope.code) {
          updateScope.code = scope.code;
        }
        this.scopeService
          .update4(this.selectedScope.id, updateScope, 'response')
          .subscribe((res) => {
            if (res.status != 200) {
              this.message.error(res.statusText);
            } else {
              this.tableDataService.onPageIndexChange(
                this.tableDataService.pageable.page!
              );
              this.isVisiableForScopeForm = false;
            }
          });
      }
    }
  }

  onCancel(name: string) {
    this.isVisiable.set(name, false);
  }

  onUserRemove(id: string, e: Event) {}

  onSysroleRemove(scopeId: string, sysroleId: string, e: Event) {
    this.scopeService.removePermissions1(scopeId, [sysroleId]).subscribe();
  }

  // for permission
  optionList: any[] = [];
  isLoading = false;
  selecteSysroles: any[] = [];

  onSearch(value: string): void {
    this.isLoading = true;
    this.sysroleService
      .all({ page: 0, size: 100 }, value === '' ? undefined : { name: value })
      .subscribe((res) => {
        this.optionList = res.content!;
        this.isLoading = false;
      });
  }

  showPermissionDialog(scope: any) {
    this.selectedScope = scope;
    this.isVisibleForPermission = true;
  }

  isVisibleForPermission: boolean = false;
  @ViewChild(SysroleSearchComponent)
  sysroleSearchComponent!: SysroleSearchComponent;
  addPermission() {
    this.scopeService
      .addPermissions1(
        this.selectedScope.id,
        this.sysroleSearchComponent.selectedUser!.map((sysrole) => sysrole.id)
      )
      .subscribe((res) => {
        this.isVisibleForPermission = false;
        this.tableDataService.onPageIndexChange(
          this.tableDataService.pageable.page!
        );
      });
  }
}
